/**
 * @Author: kun
 * 2019-10-25
 */

// @在package.json的字段_moduleAliases中定义, 表示".", 等价于"./server"
require("module-alias/register");
import * as koaLogger from "koa-logger";
import { createApplication } from "@/common/application";
import { NODE_ENV } from "@/utils/enums";
import getLogger from "@/utils/log4js";
import errorHandle from "@/middleware/error-handle";
import { WebSocketManager } from "@/service/WebSocketManager";
import { DeviceManager } from "@/service/DeviceManager";
import { AdminSocketManager } from "@/service/AdminSocketManager";
import { SchedulerManager } from "@/service/SchedulerManager";
import config from "./config";
import * as router from "./router";

const logger = getLogger("main.ts");

async function main() {
  const app = await createApplication(__dirname, Object.keys(router).map((k) => router[k]), {
    logger: getLogger("app"),
  });

  if (config.env === NODE_ENV.dev) {
    console.log("使用 koaLogger()");
    app.use(koaLogger());
  }

  console.log("使用 errorHandle()");
  app.use(errorHandle());
  console.log("监听端口 " + config.port);
  app.listen(config.port);

  console.log("初始化 init WebSocketManager");
  WebSocketManager.init(app.getHttpServer());
  console.log("初始化 init DeviceManager");
  DeviceManager.init();
  console.log("初始化 init AdminSocketManager");
  AdminSocketManager.init();
  console.log("初始化 init SchedulerManager");
  await SchedulerManager.init();
}

process.on("rejectionHandled", logger.error.bind(logger));
process.on("uncaughtException", logger.error.bind(logger));
process.on("warning", logger.warn.bind(logger));

main();
